# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     sendNote
|Author:        WYT
|date:          2020/7/1
 ----------------------------------------
|  Change Activity:
|                   2020/7/1:
-----------------------------------------
"""

import json
import time
import uuid
import datetime
import hmac
import base64
import requests
from urllib.parse import quote
from settings import sms_id, sms_secret, site_type, log_path, web_type

# 短信接口调用错误码 原因及处理方式 https://help.aliyun.com/knowledge_detail/57717.html?spm=a2c4g.11186623.2.19.10446540o63rXu
from util.DataQuery.DbTools import DbTools
from util.DataQuery.hzflowOperation import hzflowOperation
from util.Logger import Logger
from util.g import g
from util.inform.sendEmail import sendEmail


class AliyunSMS(object):
    error_handle_url = "https://help.aliyun.com/knowledge_detail/57717.html?spm=a2c4g.11186623.2.19.10446540o63rXu"

    def __init__(self):

        self.format = "JSON"
        self.version = "2017-05-25"
        self.key = sms_id
        self.secret = sms_secret
        self.signature = ""
        self.signature_method = "HMAC-SHA1"
        self.signature_version = "1.0"
        self.signature_nonce = str(uuid.uuid4())
        self.timestamp = datetime.datetime.utcnow().isoformat("T")
        self.region_id = 'cn-hangzhou'

        self.gateway = "http://dysmsapi.aliyuncs.com"
        self.action = "SendSms"
        self.sign = ""
        self.template = ""
        self.params = {}
        self.phones = ""

    def send_single(self, phone, sign="瀚中企业申报", template="SMS_193244862", params="", co_id="", year="", fb_time="",
                    res_code=""):
        """
        :param phone: 短信接收人
        :param sign: 短信签名
        :param template: 短信模板
        :param params: 短信模板参数
        :param co_id: 企业ID
        :param year: 申报年份
        :param fb_time: 撤回次数
        :param res_code: 材料种类 GR 或 PY
        :param changed_status: 修改后的短信状态 hzflow.ent_flow_data 中的 sms_status
        :param check_status: 需要对比的短信状态 作为 更新条件 默认为 0
        :return:
        """
        self.action = "SendSms"
        self.phones = phone
        self.sign = sign
        if type(params) == str:
            self.params = params
        if type(params) == dict:
            self.params = json.dumps(params)
        self.template = template

        if not res_code:
            res_code = site_type
        co_id = g.co_id if not co_id else co_id
        year = g.year if not year else year
        fb_time = g.status.get("fb_time") if not fb_time else fb_time

        query_string = self.build_query_string()
        hzflowOperation.add_note_record(co_id=co_id, year=year, fb_time=fb_time, res_code=res_code, sign=sign, phones=phone, template=template, params=params)
        resp = requests.get(self.gateway + "?" + query_string).json()
        # print(resp)
        # model = resp.get("Model")
        code = resp.get("Code")
        if code == "OK":
            # add_res = add_fun()
            # if add_res is False:
            #     # 用于主程序跳过该条记录
            #     return True
            g.logger.info(
                "短信发送成功, phone: {} sign: {} template: {} params: {} co_id: {} year: {} fb_time: {} res_code:"
                " {}".format(phone, sign, template, params, co_id, year, fb_time, res_code))
            return False
        msg = "短信发送失败, phone: {} sign: {} template: {} params: {} co_id: {} year: {} fb_time: {} res_code: {},\
         err_message: {}\n 错误处理方式详见 :  {}".format(
            phone, sign, template, params, co_id, year, fb_time, res_code, code, self.error_handle_url)
        # print(model)
        # print("send sms to %s , reason: %s" % (self.phones, resp.get("Message")))
        # print(resp)
        g.logger.error(msg)
        sendEmail(subject="autoflow_{}".format(co_id), content=msg).send_mail()
        # 用于主程序跳过该条记录
        return True

    def build_query_string(self):
        query = []
        query.append(("Format", self.format))
        query.append(("Version", self.version))
        query.append(("AccessKeyId", self.key))
        query.append(("SignatureMethod", self.signature_method))
        query.append(("SignatureVersion", self.signature_version))
        query.append(("SignatureNonce", self.signature_nonce))
        query.append(("Timestamp", self.timestamp))
        query.append(("RegionId", self.region_id))
        query.append(("Action", self.action))
        query.append(("SignName", self.sign))
        query.append(("TemplateCode", self.template))
        query.append(("PhoneNumbers", self.phones))
        params = None
        if type(self.params) == str:
            params = self.params
        elif type(self.params) == dict:
            params = json.dumps(self.params)

        query.append(("TemplateParam", params))
        query = sorted(query, key=lambda key: key[0])
        query_string = ""
        i = 0
        for item in query:
            query_string += quote(item[0], safe="~") + "=" + quote(item[1], safe="~") + "&"
            i += 1
            # print(query_string)
        # print(i)
        query_string = query_string[:-1]
        # print(query_string)
        tosign = "GET&%2F&" + quote(query_string, safe="~")
        secret = self.secret + "&"
        hmb = hmac.new(secret.encode("utf-8"), tosign.encode("utf-8"), "sha1").digest()
        self.signature = quote(base64.standard_b64encode(hmb).decode("ascii"), safe="~")
        query_string += "&" + "Signature=" + self.signature
        # g.logger.info('query_string', query_string)
        return query_string


if __name__ == '__main__':
    # pa = {"resinfo": ""}
    co_ids = [
        560629,
        409578
    ]
    res = DbTools.get_entresstatus_by_co_ids(co_ids=",".join([str(i) for i in co_ids]), year=2021)
    for status in res:
        phones = status.get("phone")
        AliyunSMS().send_single(
            phone=phones, template="SMS_193244862",
            params={"resinfo": "{},国网填报材料上传完成".format(status.get("entname"))},
            fb_time=status.get("fb_time"), res_code=web_type)

    pass
